<template>
  <div class="page-container">
    <div class="component-view">
      <!-- 操作选择 -->
      <div class="option-title">
        <span>
          <el-select
            v-model="reportVareityEn"
            style="width: 190px"
            filterable
            size="mini"
            placeholder="选择品种"
            @change="getReportContent"
          >
            <el-option
              v-for="v in varietyList"
              :key="v.variety_en"
              :value="v.variety_en"
              :label="v.variety_long_name"
            ></el-option>
          </el-select>
        </span>
        <span>选择日期</span>
        <span>
          <el-date-picker
            v-model="reportDate"
            size="mini"
            placeholder="选择报告日期"
            :clearable="false"
            @change="getReportContent"
          ></el-date-picker>
        </span>
        <span>
          <el-button size="mini" type="primary" @click="toAddReportCategory">
            新增类别
          </el-button>
        </span>
        <span>
          <el-button size="mini" type="success" @click="getReportContent">
            刷新
          </el-button>
        </span>
        <span>
          <el-button
            size="mini"
            type="infor"
            :loading="exportExcelLoading"
            :disabled="noUserOlderValues"
            @click="toExportExcel"
          >
            导出Excel
          </el-button>
        </span>
        <span>
          <el-button
            size="mini"
            type="infor"
            :loading="exportPdfLoading"
            :disabled="noUserOlderValues"
            @click="toExportPdf"
          >
            导出PDF
          </el-button>
        </span>
      </div>
      <!-- 操作 -->
      <div class="actions-box">
        <el-button
          style="width: 190px"
          type="primary"
          size="mini"
          :disabled="noUserOlderValues"
          @click="toUseOlderValue"
        >
          一键引用较旧日期数据
        </el-button>
      </div>
      <div class="action-tips">
        <div>1、若最新值和环比均显示`NAN`，则表示无当期数据；</div>
        <div>
          2、若最新值带有<span style="background-color: #ffe94e">`黄色`</span>背景，则表示旧数据非上期数据，请审慎使用；
        </div>
        <div style="display: flex; align-items: center">
          3、点击数值，可临时性手动设定最新值和环比值(系统不做保存,切页面或刷新会丢失)。
          <el-button
            style="margin-left: auto"
            type="text"
            size="mini"
            icon="el-icon-document"
          >
            <a :href="guidePdfUrl" target="_blank">操作指南</a>
          </el-button>
        </div>
      </div>
      <!-- 报告标题 -->
      <div class="report-title">
        <div class="logo-img">
          <el-image
            style="width: 100%; height: 100%"
            :src="logoImage"
            fit="fill"
          ></el-image>
        </div>
        <div>{{ reportVarietyName }}产业日报</div>
        <div>{{ reportDateTitle }}</div>
      </div>
      <!-- 分析师 -->
      <div v-show="false" style="font-size: 12px">
        <span style="margin-right: 12px">分析师：{{ reportBasic.author }}</span>
        <span style="margin-right: 12px">
          从业资格证号：{{ reportBasic.certificate1 }}
        </span>
        <span style="margin-right: 12px">
          投资咨询从业证书号：{{ reportBasic.certificate2 }}
        </span>
      </div>
      <!-- 指标 -->
      <div class="report-header">
        <div class="header-category"><span>项目类别</span></div>
        <div>
          <span class="header-index">数据指标</span>
          <span class="header-value">最新</span>
          <span class="header-diff">环比</span>
          <span class="header-index">数据指标</span>
          <span class="header-value">最新</span>
          <span class="header-diff">环比</span>
        </div>
      </div>
      <div v-loading="reportLoading">
        <!-- 指标组的显示 -->
        <div
          v-for="category in categoryList"
          :key="category.id"
          class="category-item"
        >
          <div class="category-name">
            <el-popover placement="top-start" trigger="click">
              <div>
                在【
                <span style="color: #f34d37">{{ category.category_name }}</span>
                】
              </div>
              <el-button type="text" @click="toAddCategoryIndex(category)">
                指标添加
              </el-button>
              <el-button type="text" @click="toEditCategory(category)">
                编辑类别
              </el-button>
              <el-button
                type="text"
                style="color: #f34d37"
                @click="toDeleteCategory(category)"
              >
                删除
              </el-button>
              <div>
                <el-button type="text" @click="toManageIndex(category)">
                  管理指标
                </el-button>
              </div>
              <span slot="reference">{{ category.category_name }}</span>
            </el-popover>
          </div>
          <!-- 遍历指标 -->
          <div v-if="category.category_group === 'index'" class="index-item">
            <div
              v-for="(indexItem, i) in category.showIndexes"
              :key="indexItem.id"
              :class="i % 2 === 0 ? 'index-item-even' : 'index-item-odd'"
            >
              <el-popover placement="top-start" trigger="click">
                <div>
                  <div>{{ indexItem.index_name }}</div>
                  <el-button
                    type="text"
                    size="mini"
                    @click="toEditIndex(indexItem)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="text"
                    size="mini"
                    style="color: #f34d37"
                    @click="toDeleteIndex(indexItem)"
                  >
                    删除
                  </el-button>
                </div>
                <span slot="reference" class="index-name">
                  {{ indexItem.index_name }}
                </span>
              </el-popover>
              <span v-if="indexItem.is_loaded">
                <!-- <el-tooltip :content="'上次值：' + indexItem.pre_date + '\t' + indexItem.pre_value" placement="top-start"><span class="index-value">{{ indexItem.value }}</span></el-tooltip> -->
                <!-- el-icon-minus  值不大不小的icon -->
                <el-popover
                  placement="top-start"
                  trigger="click"
                  @show="showValuePopover"
                >
                  <div style="font-weight: 700; color: #0073fc">最近值</div>
                  <div style="display: flex; align-items: center">
                    <span style="width: 80px">{{ indexItem.pre_date }}</span>
                    <span style="width: 80px; margin: 0 4px">
                      {{ indexItem.pre_value }}
                    </span>
                    <el-button
                      type="text"
                      size="mini"
                      @click="toUseOldValues(indexItem)"
                    >
                      引用
                    </el-button>
                  </div>
                  <div style="font-weight: 700; color: #0073fc">自定义数值</div>
                  <div style="display: flex; align-items: center">
                    <el-input
                      v-model="currentPopoverValue"
                      style="width: 80px"
                      placeholder="数据值"
                      size="mini"
                    ></el-input>
                    <el-input
                      v-model="currentPopoverDiff"
                      style="width: 80px; margin: 0 4px"
                      placeholder="环比值"
                      size="mini"
                    ></el-input>
                    <el-button
                      type="text"
                      size="mini"
                      @click="toEditValues(indexItem)"
                    >
                      确定
                    </el-button>
                  </div>
                  <span slot="reference">
                    <span :class="indexItem.is_far ? 'index-value far-value' : 'index-value'">
                      {{ indexItem.value }}
                    </span>
                  </span>
                </el-popover>
                <span
                  class="index-diff"
                  :class="
                    indexItem.diff > 0
                      ? 'red-text'
                      : indexItem.diff < 0
                      ? 'blue-text'
                      : ''
                  "
                >
                  {{ indexItem.diff }}
                  <i
                    :class="
                      indexItem.diff > 0
                        ? 'el-icon-top'
                        : indexItem.diff < 0
                        ? 'el-icon-bottom'
                        : ''
                    "
                  ></i>
                </span>
              </span>
              <span v-else>
                <span class="index-value">
                  <i class="el-icon-loading"></i>
                </span>
                <span class="index-diff">
                  <i class="el-icon-loading"></i>
                </span>
              </span>
            </div>
          </div>
        </div>

        <!-- 消息组的显示 -->
        <div
          v-for="(category, ci) in msgCategoryList"
          :key="category.id"
          class="category-item"
        >
          <div class="category-name">
            <el-popover placement="top-start" trigger="click">
              <el-button type="text" @click="toEditCategory(category)">
                编辑类别
              </el-button>
              <el-button type="text" @click="category.is_editor = true">
                编辑信息
              </el-button>
              <el-button
                type="text"
                @click="toDeleteCategory(category)"
                style="color: #f34d37"
              >
                删除
              </el-button>
              <span slot="reference">{{ category.category_name }}</span>
            </el-popover>
          </div>
          <!-- 显示消息 -->
          <div v-if="ci < 2" style="display: flex">
            <div v-if="category.is_editor" class="report-msg report-msg-pic">
              <el-input
                type="textarea"
                autosize
                v-model="category.message"
                @blur="saveReportMessage(category)"
              ></el-input>
            </div>
            <div
              v-else
              class="report-msg report-msg-pic"
              v-html="category.message"
              @dblclick="category.is_editor = true"
            ></div>
            <div class="msg-picture">
              <el-image
                style="width: 100%; height: 100%"
                :src="categoryImages[ci]"
                fit="fill"
              ></el-image>
            </div>
          </div>
          <div v-else>
            <div v-if="category.is_editor" class="report-msg report-msg-pic">
              <el-input
                type="textarea"
                autosize
                v-model="category.message"
                @blur="saveReportMessage(category)"
              ></el-input>
            </div>
            <div
              v-else
              class="report-msg report-msg"
              v-html="category.message"
              @dblclick="category.is_editor = true"
            ></div>
          </div>
        </div>
      </div>
      <!-- 水印 -->
      <div class="watermark" v-if="showWatermark">
        <span>瑞</span>
        <span>达</span>
        <span>研</span>
        <span>究</span>
      </div>
      <div style="font-size: 5px; margin-top: 5px">*{{ reportBasic.note }}</div>

      <!-- 类别编辑弹窗 -->
      <el-dialog
        :visible.sync="showCategoryEditDialog"
        title="项目类别编辑"
        width="500px"
      >
        <el-form label-width="80px">
          <el-form-item label="品种">
            <el-input
              disabled
              v-model="editCategory.variety_name"
              size="mini"
            ></el-input>
          </el-form-item>
          <el-form-item label="类别名称">
            <el-input
              v-model.trim="editCategory.category_name"
              size="mini"
              placeholder="输入新的项目类别的名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="类别组">
            <el-select
              v-model="editCategory.category_group"
              :disabled="editCategoryDisabled"
              style="width: 100%"
            >
              <el-option value="index" label="指标组"></el-option>
              <el-option value="msg" label="消息组"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="序号">
            <el-input
              v-model.trim="editCategory.sorted"
              placeholder="项目类别的排序序号,小->大"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button
            type="infor"
            size="mini"
            @click="showCategoryEditDialog = false"
          >
            取消
          </el-button>
          <el-button type="primary" size="mini" @click="toSaveCategory">
            保存
          </el-button>
        </div>
      </el-dialog>

      <!-- 类别下指标编辑弹窗 -->
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="showIndexEditDialog"
        :title="indexDialogTitle"
        width="600px"
      >
        <el-form label-width="80px">
          <el-form-item label="指标查找">
            <el-select
              v-model="editIndex.index_source_id"
              @change="categoryIndexChange"
              filterable
              remote
              :remote-method="queryIndexList"
              placeholder="输入关键字查询系统内的指标"
              style="width: 100%"
            >
              <el-option
                v-for="inx in indexesList"
                :value="inx.id"
                :label="inx.name_zh"
                :key="inx.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="运算符号">
            <span>
              <el-button
                size="mini"
                type="primary"
                @click="makeCalculateFormula('+')"
              >
                加
              </el-button>
              <el-button
                size="mini"
                type="primary"
                @click="makeCalculateFormula('-')"
              >
                减
              </el-button>
              <el-button
                size="mini"
                type="primary"
                @click="makeCalculateFormula('*')"
              >
                乘
              </el-button>
              <el-button
                size="mini"
                type="primary"
                @click="makeCalculateFormula('/')"
              >
                除
              </el-button>
              <el-button
                size="mini"
                type="primary"
                @click="makeCalculateFormula('(')"
              >
                (
              </el-button>
              <el-button
                size="mini"
                type="primary"
                @click="makeCalculateFormula(')')"
              >
                )
              </el-button>
              <el-button size="mini" type="primary" @click="addNumberToFormula">
                常数
              </el-button>
              <el-input
                v-model="cacheNumber"
                placeholder="输入常数值"
                style="width: 110px; margin-left: 4px"
                size="mini"
              ></el-input>
            </span>
          </el-form-item>
          <el-form-item label="值公式">
            <div style="display: flex; align-items: center">
              <el-input disabled v-model="editIndex.formula"></el-input>
              <i
                @click="toClearFormula"
                class="el-icon-delete-solid"
                style="margin-left: 5px; color: #f34d37; cursor: pointer"
              ></i>
            </div>
          </el-form-item>
          <el-form-item label="显示名称">
            <el-input
              v-model="editIndex.index_name"
              placeholder="用于显示在报告上的名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="序号">
            <el-input
              v-model.trim="editIndex.sorted"
              placeholder="由小->大序号,从左->右显示"
            ></el-input>
          </el-form-item>
          <el-form-item label="显示">
            <el-switch v-model="editIndex.is_active"></el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <span style="margin-right: 10px; color: #ff0000">
            需构建正确的数学逻辑公式,程序没有对公式进行验证!
          </span>
          <el-button
            type="infor"
            size="mini"
            @click="showIndexEditDialog = false"
          >
            取消
          </el-button>
          <el-button type="primary" size="mini" @click="toSaveIndex">
            保存
          </el-button>
        </div>
      </el-dialog>

      <!-- 类别下指标管理弹窗 -->
      <el-dialog :visible.sync="showIndexMagDialog" :title="manageIndexesTitle">
        <div style="padding: 8px 15px">
          <el-table :data="currentDialogIndexes">
            <el-table-column prop="id" label="ID" width="100" />
            <el-table-column
              prop="index_name"
              label="指标名称"
              width="280px"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="formula"
              label="公式"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column label="显示" width="70px">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.activeShow"
                  @change="
                    (flag) => {
                      categoryIndexShowChange(flag, scope.row)
                    }
                  "
                ></el-switch>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  let NAME_SPACE = 'V01' // 报告
  import { baseURL } from '@/config'
  import { getEDBTables, getFormulaIndexLinkRatio } from '@/api/edbdata/datalib'
  import { getUserAuthVariety } from '@/api/operations/variety'
  import { datetimeToStr } from '@/utils/datetimeUtils'
  import { getItemInArray } from '@/utils/dataUtils'
  import {
    saveDailyReportCateogy,
    getDailyReportCategoy,
    saveDailyReportIndex,
    saveDailyReportMessage,
    deleteDailyReportCategory,
    deleteDailyReportIndex,
    exportDailyReportAsExcel,
    exportDailyReportAsPdf,
  } from '@/api/regularReport/dailyReport'
  export default {
    data() {
      return {
        guidePdfUrl: baseURL + '/storagefile/AppFiles/guide/构建品种日报.pdf',
        reportLoading: false,
        showWatermark: false,
        varietyList: [],
        categoryList: [
          // {id:1, category_name: '期货市场', sorted: 1,
          //  indexes: [
          //    {id: '0001', index_name: '郑棉仓单（张）', value: 15821, diff: -71, category_id: 1, formula: ''},
          //  ]
          // },
        ],
        msgCategoryList: [],

        reportVareityEn: '',
        reportDate: new Date(),
        reportDateTitle: '',

        showCategoryEditDialog: false,
        editCategoryDisabled: false,
        editCategory: {
          variety_name: '',
          variety_en: '',
          category_name: '',
          category_group: 'index',
          sorted: 1,
        },

        // 待选指标
        indexesList: [],
        showIndexEditDialog: false,
        indexDialogTitle: '',
        cacheNumber: 0,
        editIndex: {
          index_source_id: null, // 指标的系统id
          id: -1, // 传给后端，得知是修改还是新增
          category_id: -1,
          index_name: '',
          formula: '',
          frequency: '',
          sorted: 1,
          is_active: true,
        },
        // 类别内指标管理弹窗
        showIndexMagDialog: false,
        // 类别内指标列表
        currentDialogIndexes: [],
        manageIndexesTitle: '',

        // 标题
        reportVarietyName: '',
        // 图片
        logoImage: require('@/assets/qr_logo/company_logo.png'),
        categoryImages: [
          require('@/assets/qr_logo/yjyqrcode.png'),
          require('@/assets/qr_logo/wxkfqrcode.png'),
        ],
        // 基本信息
        reportBasic: {
          author: '',
          certificate1: '',
          certificate2: '',
          note: '',
        },
        // 循环获取指标的timer
        loopIndexValueTimer: null,

        exportExcelLoading: false,
        exportPdfLoading: false,

        // 当前自定义值
        currentPopoverValue: null,
        currentPopoverDiff: null,
        noUserOlderValues: true,
      }
    },
    mounted() {
      let today = new Date()
      if (today.getHours() < 15) {
        today = new Date(new Date().getTime() - 24 * 60 * 60 * 1000)
      }
      this.reportDate = today
      this.reportDateTitle = datetimeToStr(this.reportDate, true, '-')
      this.getVariety()
    },
    methods: {
      // 数值弹出框事件
      showValuePopover() {
        this.currentPopoverValue = null
        this.currentPopoverDiff = null
      },

      // 自定义数据填入
      toEditValues(indexItem) {
        let value = parseFloat(this.currentPopoverValue)
        let diff = parseFloat(this.currentPopoverDiff)
        if (Number.isNaN(value) || Number.isNaN(diff)) {
          return
        }
        indexItem.value = value
        indexItem.diff = diff
      },

      // 请求系统所有品种
      getVariety() {
        getUserAuthVariety({ space: NAME_SPACE }).then((res) => {
          this.varietyList = res.data
        })
      },

      // 查询数据指标
      queryIndexList(name) {
        if (!name) return
        const params = {
          kw: name,
          page: 1,
          page_size: 9999,
        }
        getEDBTables(params).then((res) => {
          this.indexesList = res.data.records
        })
      },

      // 引用旧时间的数据到当前
      toUseOldValues(indexItem) {
        indexItem.value = indexItem.pre_value
        indexItem.diff = indexItem.pre_diff
      },

      // 一键引用旧时间的数据到当前
      toUseOlderValue() {
        for (let i = 0; i < this.categoryList.length; i++) {
          let categoryObj = this.categoryList[i]
          if (!categoryObj.showIndexes || categoryObj.showIndexes.length < 1)
            continue
          for (let j = 0; j < categoryObj.showIndexes.length; j++) {
            let indexObj = categoryObj.showIndexes[j]
            if (indexObj.value === 'NAN') {
              indexObj.value = indexObj.pre_value
              indexObj.diff = indexObj.pre_diff
            }
          }
        }
      },

      // 查询日报指标的具体数值和环比
      getIndexLinkRatio(indexItem) {
        indexItem.query_date = this.reportDateTitle
        getFormulaIndexLinkRatio(indexItem)
          .then((res) => {
            // console.log('查询指标数据', indexItem);
            const data = res.data
            indexItem.pre_date = data.pre_date
            indexItem.pre_value = data.pre_value
            indexItem.pre_diff = data.pre_diff
            indexItem.value = data.value
            indexItem.diff = data.diff
            indexItem.is_far = data.is_far
            indexItem.is_loaded = true
          })
          .catch(() => {
            indexItem.pre_date = 'ERR'
            indexItem.pre_value = 'ERR'
            indexItem.value = 'ERR'
            indexItem.diff = 'ERR'
            indexItem.is_far = false
            indexItem.is_loaded = true
          })
      },

      // 循环指标
      loopIndexTask() {
        if (this.categoryList.length < 1) return
        let taskFinished = true
        for (let i = 0; i < this.categoryList.length; i++) {
          let categoryObj = this.categoryList[i]
          if (!categoryObj.showIndexes || categoryObj.showIndexes.length < 1)
            continue
          for (let j = 0; j < categoryObj.showIndexes.length; j++) {
            // 请求数据指标的数据
            let indexObj = categoryObj.showIndexes[j]
            if (!indexObj.is_loaded) {
              taskFinished = false
              this.getIndexLinkRatio(indexObj) // 请求指标
              break
            } else {
              taskFinished = true // 没有请求指标
            }
          }
          if (!taskFinished) {
            break // 内部有指标正在请求，跳出
          }
        }
        if (taskFinished) {
          // 数据都请求完成
          console.log('数据全部请求完成')
          clearInterval(this.loopIndexValueTimer)
          this.noUserOlderValues = false
        }
      },

      // 获取日报内容
      getReportContent() {
        let currentVariety = getItemInArray(
          'variety_en',
          this.reportVareityEn,
          this.varietyList
        )
        if (!currentVariety) {
          this.$baseMessage('请选择正确的品种!', 'error')
          return
        }
        // 设定标题
        this.reportVarietyName = currentVariety.variety_name
        this.reportDateTitle = datetimeToStr(this.reportDate, true, '-')
        const param = {
          v: this.reportVareityEn,
          date: this.reportDateTitle.replaceAll('-', ''),
        }
        this.reportLoading = true
        this.noUserOlderValues = true
        getDailyReportCategoy(param)
          .then((res) => {
            const data = res.data
            this.categoryList = data.index_categories.map((ct) => {
              ct.showIndexes = ct.indexes.filter((i) => i.is_active === 1)
              return ct
            })
            this.msgCategoryList = data.msg_categories.map((item) => {
              item.is_editor = false
              return item
            })
            // console.log(this.categoryList);
            this.reportBasic.author = data.author
            this.reportBasic.certificate1 = data.certificate1
            this.reportBasic.certificate2 = data.certificate2
            this.reportBasic.note = data.note
            this.reportLoading = false
            // 请求数据
            if (this.loopIndexValueTimer) {
              clearInterval(this.loopIndexValueTimer)
            }
            this.loopIndexValueTimer = setInterval(this.loopIndexTask, 250) // 间隔请求不至于后端压力大
          })
          .catch(() => {
            this.$baseMessage('报告内容加载出错了！', 'error')
            this.reportLoading = false
          })
      },

      // 导出excel
      toExportExcel() {
        if (!this.reportVareityEn || this.categoryList.length < 1) {
          this.$baseMessage('请先刷新报告数据再导出!', 'error')
          return
        }
        const contentData = {
          report_title: this.reportVarietyName + '产业日报',
          report_date: this.reportDateTitle,
          author: {
            name: this.reportBasic.author,
            certificate1: this.reportBasic.certificate1,
            certificate2: this.reportBasic.certificate2,
          },
          note: this.reportBasic.note,
          index_categories: this.categoryList,
          msg_categories: this.msgCategoryList,
          variety_en: this.reportVareityEn,
        }
        // 导出
        this.exportExcelLoading = true
        exportDailyReportAsExcel(contentData)
          .then((res) => {
            let a = document.createElement('a')
            a.href = res.data.report_file
            a.style.display = 'none'
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
            this.exportExcelLoading = false
          })
          .catch(() => {
            this.$baseMessage('导出失败!', 'error')
            this.exportExcelLoading = false
          })
      },

      // 导出PDF
      toExportPdf() {
        if (!this.reportVareityEn || this.categoryList.length < 1) {
          this.$baseMessage('请先刷新报告数据再导出!', 'error')
          return
        }
        // 检测是否还含NAN的指标
        for (let i = 0; i < this.categoryList.length; i++) {
          const ctg = this.categoryList[i]
          for (let j = 0; j < ctg.indexes.length; j++) {
            const idx = ctg.indexes[j]
            if (idx.is_active === 1 && idx.value === 'NAN') {
              this.$baseMessage(
                '检测指标中含有NAN数据.请先检查处理后再导出',
                'error'
              )
              return
            }
          }
        }
        const contentData = {
          report_title: this.reportVarietyName + '产业日报',
          report_date: this.reportDateTitle,
          author: {
            name: this.reportBasic.author,
            certificate1: this.reportBasic.certificate1,
            certificate2: this.reportBasic.certificate2,
          },
          note: this.reportBasic.note,
          index_categories: this.categoryList,
          msg_categories: this.msgCategoryList,
          variety_en: this.reportVareityEn,
        }
        // 导出
        this.exportPdfLoading = true
        exportDailyReportAsPdf(contentData)
          .then((res) => {
            let a = document.createElement('a')
            a.href = res.data.report_file
            a.style.display = 'none'
            a.target = '_blank'
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
            this.exportPdfLoading = false
          })
          .catch(() => {
            this.$baseMessage('导出失败!', 'error')
            this.exportPdfLoading = false
          })
      },

      // 新增大类别
      toAddReportCategory() {
        let curVname = getItemInArray(
          'variety_en',
          this.reportVareityEn,
          this.varietyList
        )
        if (!curVname) {
          this.$baseMessage('请先选择品种再添加!', 'error')
          return
        }
        this.editCategory.variety_en = this.reportVareityEn
        this.editCategory.variety_name = curVname.variety_name
        this.editCategory.category_name = ''
        this.editCategory.category_group = 'index'
        this.editCategory.sorted = 1
        this.editCategoryDisabled = false
        this.showCategoryEditDialog = true
      },

      // 保存编辑的类别
      toSaveCategory() {
        saveDailyReportCateogy(this.editCategory).then((res) => {
          if (res.code === 200) {
            this.$baseMessage(res.msg, 'success')
            // 将类别显示出来
            let newCategory = Object.assign(res.data, { showIndexes: [] })
            this.categoryList.push(newCategory)
            this.showCategoryEditDialog = false
          } else {
            this.$baseMessage(res.msg, 'error')
          }
        })
      },

      // 保存编辑的指标
      toSaveIndex() {
        if (!this.editIndex.index_name || !this.editIndex.formula) {
          this.$baseMessage('请设置指标信息再操作!', 'error')
          return
        }
        this.saveCategoryIndexObj(this.editIndex)
      },

      // 使用category_id获取大类
      getCategoryObjectIndex(categoryId) {
        let categoryIndex = -1
        for (let i = 0; i < this.categoryList.length; i++) {
          if (this.categoryList[i].id === categoryId) {
            categoryIndex = i
            break
          }
        }
        return categoryIndex
      },

      // 保存编辑的指标
      saveCategoryIndexObj(obj) {
        saveDailyReportIndex(obj).then((res) => {
          if (res.code === 200) {
            this.$baseMessage(res.msg, 'success')
            this.showIndexEditDialog = false
            // 将指标加入到响应的列表中
            const categoryIndex = this.getCategoryObjectIndex(obj.category_id)
            if (categoryIndex > -1) {
              let showIndex = Object.assign(res.data, { is_loaded: true })
              this.categoryList[categoryIndex].showIndexes.push(showIndex)
            }
          } else {
            this.$baseMessage(res.msg, 'error')
          }
        })
      },

      // 在大类里添加数据指标
      toAddCategoryIndex(category) {
        this.indexDialogTitle = '在【' + category.category_name + '】编辑指标'
        this.editIndex.id = -1
        this.editIndex.category_id = category.id
        this.editIndex.index_name = ''
        this.editIndex.formula = ''
        this.editIndex.sorted = 1
        this.editIndex.index_source_id = null
        this.showIndexEditDialog = true
      },

      // 编辑大类
      toEditCategory(category) {
        this.editCategory.variety_en = category.variety_en
        this.editCategory.variety_name = category.variety_name
        this.editCategory.category_name = category.category_name
        this.editCategory.category_group = category.category_group
        this.editCategory.sorted = category.sorted
        this.editCategoryDisabled = true
        this.showCategoryEditDialog = true
      },

      // 管理大类下的指标
      toManageIndex(category) {
        // 弹窗显示指标
        this.manageIndexesTitle = `【${category.category_name}】指标管理`
        this.currentDialogIndexes = JSON.parse(
          JSON.stringify(category.indexes)
        ).map((item) => {
          item.activeShow = item.is_active === 1 ? true : false
          return item
        })
        this.showIndexMagDialog = true
      },

      // 指标变化
      categoryIndexShowChange(flag, indexItem) {
        indexItem.is_active = flag ? 1 : 0
        this.saveCategoryIndexObj(indexItem)
      },

      // 删除大类
      toDeleteCategory(category) {
        this.$baseConfirm('删除将不可恢复？', null, () => {
          deleteDailyReportCategory({ cid: category.id }).then((res) => {
            if (res.code === 200) {
              this.getReportContent()
              this.$baseMessage(res.msg, 'success')
            } else {
              this.$baseMessage(res.msg, 'error')
            }
          })
        })
      },

      // 保存消息
      saveReportMessage(category) {
        category.is_editor = false
        const msgData = {
          report_date: this.reportDateTitle,
          variety_en: this.reportVareityEn,
          category_id: category.id,
          message: category.message,
        }
        saveDailyReportMessage(msgData).then((res) => {
          this.$baseMessage(res.msg, res.code === 200 ? 'success' : 'error')
        })
      },

      // 编辑指标
      toEditIndex(indexItem) {
        this.indexDialogTitle = '编辑指标信息'
        this.editIndex.id = indexItem.id
        this.editIndex.category_id = indexItem.category_id
        this.editIndex.index_name = indexItem.index_name
        this.editIndex.formula = indexItem.formula
        this.editIndex.sorted = indexItem.sorted
        this.editIndex.frequency = indexItem.frequency
        this.showIndexEditDialog = true
      },

      // 删除指标
      toDeleteIndex(indexItem) {
        this.$baseConfirm('删除该指标将不可恢复？', null, () => {
          deleteDailyReportIndex({ iid: indexItem.id }).then((res) => {
            if (res.code === 200) {
              this.getReportContent()
              this.$baseMessage(res.msg, 'success')
            } else {
              this.$baseMessage(res.msg, 'error')
            }
          })
        })
      },

      // 清空公式
      toClearFormula() {
        this.editIndex.formula = ''
        this.editIndex.index_source_id = null //清空当前选中指标
        this.editIndex.index_name = ''
      },

      // 选中指标的变化事件
      categoryIndexChange(value) {
        let indexObj = getItemInArray('id', value, this.indexesList)
        if (!indexObj) {
          this.$baseMessage('指标选择出错了!', 'error')
          return
        }
        let val = `${indexObj.source_plat}_${indexObj.source_id}`
        this.makeCalculateFormula(val)
        this.editIndex.frequency = indexObj.frequency
        // 显示名称
        this.editIndex.index_name = `${indexObj.name_zh}(${indexObj.frequency},${indexObj.unit})`
      },

      // 设置公式
      makeCalculateFormula(val) {
        this.editIndex.formula += val
      },

      addNumberToFormula() {
        let num = parseFloat(this.cacheNumber)
        if (!num) return
        this.makeCalculateFormula(num + '')
      },
    },
  }
</script>

<style scoped lang="scss">
  $categoryWidth: 820px; /*820=720+100*/
  $indexRowWidth: 720px;
  $indexWidth: 360px; /*360=240+50+70*/
  $indexNameWidth: 240px;
  $indexValueWidth: 48px; /*让2px给行中间的间隔(分10px给diff)*/
  $indexDiffWidth: 67px; /*让2px给行中间的间隔，让1px给奇数行中间的虚线分割*/

  .red-text {
    color: #ff0000;
  }
  .blue-text {
    color: #0000ff;
  }
  .component-view {
    width: $categoryWidth;
    padding: 10px;
    .option-title {
      display: flex;
      align-items: center;
      span {
        margin-right: 5px;
      }
    }
    .actions-box {
      padding: 10px 0;
      display: flex;
      align-items: center;
    }
    .action-tips {
      color: #ff0000;
      border-bottom: 1px dashed #666;
      padding-bottom: 10px;
    }
  }
  .watermark {
    user-select: none;
    transform: rotate(-30deg);
    z-index: 1;
    position: absolute;
    top: 280px;
    left: 140px;
    width: 700px;
    height: 150px;
    opacity: 0.6;
    color: rgba($color: #fbc9c9, $alpha: 0.6);
    font-size: 100px;
    line-height: 150px;
    span {
      margin: 0 30px;
    }
  }
  .report-title {
    display: flex;
    justify-content: space-between;
    font-size: 30px;
    font-weight: 700;
    line-height: 50px;
    align-items: center;
    .logo-img {
      width: 150px;
      height: 44px;
    }
  }
  .report-header {
    display: flex;
    line-height: 26px;
    background-color: #0f6fc6;
    color: #fff;
    font-weight: 700;
    font-size: 14px;
    .header-category {
      width: 100px;
      text-align: center;
    }
    .header-index {
      width: $indexNameWidth;
      display: inline-block;
      text-align: center;
    }
    .header-value {
      width: $indexValueWidth;
      display: inline-block;
      text-align: right;
    }
    .header-diff {
      width: $indexDiffWidth;
      display: inline-block;
      text-align: right;
    }
  }
  .category-item {
    display: flex;
    border-bottom: 2px solid #000;
    width: $categoryWidth;
    .report-msg {
      font-size: 11px;
      line-height: 22px;
      padding: 2px;
      white-space: pre-line;
      &-pic {
        width: 600px; // 720-120
      }
    }
    .msg-picture {
      min-width: calc(#{$indexDiffWidth} + #{$indexValueWidth});
      width: calc(#{$indexDiffWidth} + #{$indexValueWidth});
      height: calc(#{$indexDiffWidth} + #{$indexValueWidth});
      margin: 2px 0;
      background-color: #555555;
      margin-left: 0 auto;
    }
    .category-name {
      min-width: 98px; /*让2px给右边线*/
      width: 98px; /*让2px给右边线*/
      border-right: 2px solid #000;
      /*内部元素居中*/
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .index-item {
      width: $indexRowWidth;
      display: flex;
      flex-wrap: wrap;
      font-size: 10px;
      line-height: 22px;
      &-even {
        padding-right: 2px;
        border-right: 1px dashed #000;
      }
      &-odd {
        padding-left: 2px;
      }
      .index-name {
        display: inline-block;
        padding-left: 2px;
        width: $indexNameWidth;
      }
      .index-value {
        display: inline-block;
        width: $indexValueWidth;
        text-align: right;
        font-weight: 700;
      }
      .far-value {
        background-color: #ffe94e;
      }
      .index-diff {
        display: inline-block;
        width: $indexDiffWidth;
        text-align: right;
        font-weight: 700;
      }
    }
  }
</style>
